import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const isAuthenticated = ref(false)
  const userType = ref('') // 'admin' or 'student'
  const token = ref('')
  const userInfo = ref({})

  // 登录
  const login = async (credentials, type) => {
    try {
      // 模拟登录API调用
      // const response = await authAPI.login(credentials, type)
      
      // 模拟数据
      const mockResponse = {
        token: 'mock-token-' + Date.now(),
        userInfo: {
          id: 1,
          name: type === 'admin' ? '管理员' : '张三',
          username: credentials.username || credentials.phone,
          type: type
        }
      }
      
      token.value = mockResponse.token
      userInfo.value = mockResponse.userInfo
      userType.value = type
      isAuthenticated.value = true
      
      // 存储到localStorage
      localStorage.setItem('token', mockResponse.token)
      localStorage.setItem('userInfo', JSON.stringify(mockResponse.userInfo))
      localStorage.setItem('userType', type)
      
      return { success: true, data: mockResponse }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  // 登出
  const logout = () => {
    isAuthenticated.value = false
    userType.value = ''
    token.value = ''
    userInfo.value = {}
    
    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userType')
  }

  // 初始化认证状态
  const initAuth = () => {
    const savedToken = localStorage.getItem('token')
    const savedUserInfo = localStorage.getItem('userInfo')
    const savedUserType = localStorage.getItem('userType')
    
    if (savedToken && savedUserInfo && savedUserType) {
      token.value = savedToken
      userInfo.value = JSON.parse(savedUserInfo)
      userType.value = savedUserType
      isAuthenticated.value = true
    }
  }

  return {
    isAuthenticated,
    userType,
    token,
    userInfo,
    login,
    logout,
    initAuth
  }
})